class ProfilesController < ApplicationController
  layout "general"
  before_filter :login_required, :except => [:show]
  verify :only => :update, :method => :post, :redirect_to => {:controller => 'schools', :action => 'homepage'}
  
  def edit
    begin
      @profile = Profile.find(:first, :conditions => ["user_id = ?", self.current_user.id])
    rescue ActiveRecord::RecordNotFound
      @profile = Profile.new
    end
  end
  
  def update_offline
    @profile = Profile.find(:first, :conditions => ["user_id = ?", self.current_user.id])
    unless @profile.blank?
      @profile.update_attributes!(params[:profile])
    else
      @profile ||= Profile.new(params[:profile])
      @profile.user = self.current_user
      @profile.save!
    end
    bc = Broadcast.create(:site => 1, :from=>0, :to=>0, :content=>"<a href=\"#{user_path(self.current_user)}\">#{self.current_user.login}</a> 刚刚编辑了他/她的个人资料，看看是何方人士 ^^")
    
    respond_to do |format|
      format.html {redirect_to home_path }
    end
  end
  
  def update_online
    @user = User.find(params[:id])
    
    # convert user's avatar to gif format, thanks for Robin Lu
    iconfile = params[:user][:avatar_url]
    unless iconfile.blank?
      # if user upload avatar, convert file format
      img = ::Magick::Image::from_blob(iconfile.read).first
      img.crop_resized!(72,72)
      filename = File.join(RAILS_ROOT + "/public/user/avatar_url/tmp", 'icon.gif')
      img.write(filename)
      iconfile = File.open(filename)
      params[:user][:avatar_url] = iconfile
    end
    
    # correct url
    urls = %w(delicious douban yupoo fanfou twitter)
    urls.each do |url|
      tmp = params[:user]["#{url}_url".to_sym]
      params[:user]["#{url}_url".to_sym] = correct_url(tmp)
    end

    if @user.update_attributes(params[:user])
      #flash[:notice] = "你已经更新了个人资料"
      bc = Broadcast.create(:site => 1, :from=>0, :to=>0, :content=>"<a href=\"#{user_path(self.current_user)}\">#{self.current_user.login}</a> 刚刚修改了他/她的头像和网上据点")
      redirect_to home_path
    else
      #flash[:notice] = "个人资料更新失败"
      redirect_to :controller => 'profiles', :action => 'edit'
    end
  end
  
  protected
  def correct_url(url)
    unless url.to_s.empty?
      unless url =~ /^http\:\/\//
        "http://#{url}"
      else
        url
      end
    end
  end
end
